using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using System.Web.UI;

namespace By1eEurope.BKS.Controls
{
    /// <summary>
    /// Decides based on a bool'sch expression about the content of fields of the current page
    /// </summary>
    public class FieldContentAnalyser : IExpressionAnalyser
    {
        #region IExpressionAnalyser Members

        public bool AnalyseExpression(string expression, HttpRequest request, HttpContext context)
        {
            SPListItem currentPage = SPContext.Current.ListItem;
            string[] terms = expression.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
            bool or = false; //neutralelemnt of OR operation
            foreach (string term in terms)
            {
                string[] fields = term.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                bool and = true; // neutralelement of AND operation
                foreach (string field in fields)
                {
                    string field2 = field;
                    bool invert = false;
                    if (field.StartsWith("!"))
                    {
                        field2 = field.Substring(1);
                        invert = true;
                    }

                    if (currentPage.Fields.ContainsField(field2))
                        and &= !string.IsNullOrEmpty(currentPage[field2] + "");
                    else
                        and &= false;

                    if (invert)
                        and = !and;
                }
                or |= and;
            }
            return or;
        }

        #endregion
    }
}
